package com.atguigu.bio;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {

    private static Logger logger = LoggerFactory.getLogger(BIOServer.class);

    public static void main(String[] args) throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        final ServerSocket serverSocket = new ServerSocket(6666);
        logger.info("服务启动了");
        while (true) {
            final Socket socket = serverSocket.accept();
            logger.info("连接到一个客户端");

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    handler(socket);
                }
            });
        }


    }

    public static void handler(Socket socket) {

        logger.info("当前线程:{}",Thread.currentThread().getName());

        byte[] bytes = new byte[1024];
        try (InputStream inputStream = socket.getInputStream()) {
            while (true) {
                logger.info("当前线程:{}",Thread.currentThread().getName());

                int read = inputStream.read(bytes);
                if (read == -1) {
                    break;
                }
                System.out.println(new String(bytes,0,read));

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
